package video

import (
	"babyplan/internal/common/constant"
	"babyplan/model"
	"babyplan/model/common"
	"cftgo/cftc"
	"cftgo/cftc/convert"
	"cftgo/cftf/boot/app"
	"cftgo/cftf/db"
	"cftgo/cftf/ginhelper"
	"cftgo/cftf/uuid"
	"errors"
	"io"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"
)

type Video struct {
}

func (this *Video) Info(c *gin.Context) {
	id := c.Param("id")
	video := model.Video{}
	result := db.GetOrmDb(constant.BABYPLANT_DB).First(&video, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			ginhelper.RspErr(c, 1, "not found record")
			return
		} else {
			ginhelper.RspErr(c, 500, "server internal error")
			return
		}
	}
	ginhelper.RspData(c, video.ToVo())
}

func (this *Video) Update(c *gin.Context) {
	reqObj := struct {
		Bookmarks []common.Bookmark `gorm:"comment:bookmarks"`
	}{}
	if err := c.ShouldBindJSON(&reqObj); err != nil {
		ginhelper.RspErr(c, 1, "params format error")
		return
	}
	id := c.Param("id")
	video := model.Video{}
	result := db.GetOrmDb(constant.BABYPLANT_DB).First(&video, id)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			ginhelper.RspErr(c, 1, "not found record")
			return
		} else {
			ginhelper.RspErr(c, 500, "server internal error")
			return
		}
	}
	now := app.GetRealSeconds()
	video.Bookmarks = reqObj.Bookmarks
	video.UpdatedAt = now
	result = db.GetOrmDb(constant.BABYPLANT_DB).Save(&video)
	if result.Error != nil {
		ginhelper.RspErr(c, 500, "server internal error")
		return
	}
	ginhelper.RspOk(c)
}

func (this *Video) Upload(c *gin.Context) {
	albumId := convert.ToInt64(c.DefaultQuery("album_id", ""))
	albumModel := new(model.Album)
	result := db.GetOrmDb(constant.BABYPLANT_DB).Where("entity_id = ?", albumId).First(albumModel)
	if result.Error != nil {
		if errors.Is(result.Error, gorm.ErrRecordNotFound) {
			ginhelper.RspErr(c, 1, "not found record")
			return
		} else {
			ginhelper.RspErr(c, 500, "server internal error")
			return
		}
	}
	bodyBytes, err := io.ReadAll(c.Request.Body)
	if err != nil {
		ginhelper.RspErr(c, 500, "server internal error")
		return
	}
	defer c.Request.Body.Close()
	strs := cftc.StrSplit(string(bodyBytes), "\n")
	now := app.GetRealSeconds()
	for _, str := range strs {
		videoModel := new(model.Video)
		videoModel.EntityId = cftc.EntityId(uuid.NewNodeUuid())
		videoModel.AlbumId = cftc.EntityId(albumId)
		videoModel.FileName = str
		videoModel.UpdatedAt = now
		videoModel.CreatedAt = now
		result := db.GetOrmDb(constant.BABYPLANT_DB).Create(&videoModel)
		if result.Error != nil {
			ginhelper.RspErr(c, 500, "server internal error")
			return
		}
	}
	ginhelper.RspOk(c)
}
